#include "logmodel.h"
#include <QDebug>

LogModel::LogModel(QObject *parent) :
    QAbstractListModel(parent)
{
}
int LogModel::rowCount(const QModelIndex & parent) const
{
    return m_list.count();
}

QVariant LogModel::data(const QModelIndex & index, int role) const
{
    if (index.row() < 0 || index.row() >= m_list.count())
        return QVariant();

    LogItem log = m_list[index.row()];
    QString str;
    if (role == TypeRole)
        str = log.type;
    else if (role == VersionRole)
        str =  log.version;
    else if (role == LineRole)
        str = QString::number( log.line );
    else if (role == FileRole)
        str =  log.file;
    else if (role == FunctionRole)
        str =  log.function;
    else if (role == CategoryRole)
        str =  log.category;
    else if (role == MsgRole)
        str =  log.msg;
    else if (role == TimeRole)
        str =  log.datetime.toString("yyMMdd HH:mm:ss.zzz");
    else if(role == MsgOnlyRole)
        return log.msg;

    if(log.type == "d")
        str = "<font color=\"blue\">" + str + "</font>";
    else if(log.type == "w")
        str = "<font color=\"orangered\">" + str + "</font>";
    else if(log.type == "c")
        str = "<font color=\"crimson\">" + str + "</font>";
    else if(log.type == "e")
        str = "<font color=\"blueviolet\">" + str + "</font>";
        return str;
//    return QVariant();
}

QHash<int, QByteArray> LogModel::roleNames() const
{

    QHash<int, QByteArray> roles;
    roles[TypeRole] = "rType";
    roles[VersionRole] = "rVersion";
    roles[LineRole] = "rLine";
    roles[FileRole] = "rFile";
    roles[FunctionRole] = "rFunction";
    roles[CategoryRole] = "rCategory";
    roles[MsgRole] = "rMsg";
    roles[TimeRole] = "rTime";
    roles[MsgOnlyRole] = "rMsgOnly";
    return roles;
}

void LogModel::clear()
{
    beginResetModel();
    m_list.clear();
    endResetModel();
}

void LogModel::add(const LogItem &log)
{
    qDebug()<< log.msg;
    beginInsertRows(QModelIndex(), m_list.size(), m_list.size());
    m_list << log;
    endInsertRows();
}

